package com.shihuituan.order.utils

import com.shihuituan.order.service.OrderServiceImpl;
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.spockframework.runtime.Sputnik;
import spock.lang.Specification;

/**
 * 描述：测试静态方法
 * 关于Mock静态方法的解释，一个参考【美团技术团队】的这篇文章
 * https://tech.meituan.com/2021/08/06/spock-practice-in-meituan.html
 * @author hudongkang
 * @date 2021-09-14 10:48
 */
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Sputnik.class)
@PrepareForTest(MathUtils.class)
@SuppressStaticInitializationFor("com.shihuituan.order.utils.MathUtils")
public class MathUtilsSpec extends Specification {


    /**
     * 被测试的目标类
     * 这个类中的被测试方法，执行了一个MathUtils类的静态方法
     * 本案例中就是要对这个MathUtils类的静态方法进行Mock
     */
    def target = new OrderServiceImpl();
    /**
     * 前置方法
     * @return
     */
    def setup(){
        //Mock静态方法所在的类
        PowerMockito.mockStatic(MathUtils.class)
    }


    def "测试静态方法案例"(){
        given: "给定以下入参数据"
        def arr = [5,7,8,6,5,4,1,3,9,10]

        and: "模拟静态方法返回值"
        PowerMockito.when(MathUtils.max(Mockito.any())).thenReturn(10)
        PowerMockito.when(MathUtils.min(Mockito.any())).thenReturn(1)

        when: "调用被测试的方法"
        int average = target.maxAndMinAverage(arr)

        then: "期望结果"
        average == 5
    }





}
